package com.schedule.coursesystem;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/user")
public class UserController {
    private static final File file = new File("users.json");
    private static final ObjectMapper mapper = new ObjectMapper();
    private static List<User> userList = loadUsers();

    private static List<User> loadUsers() {
        try {
            if (!file.exists()) return new ArrayList<>();
            return mapper.readValue(file, new TypeReference<>() {});
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    private static void saveUsers() {
        try {
            mapper.writeValue(file, userList);
        } catch (Exception ignored) {}
    }

    @PostMapping("/register")
    public String register(@RequestBody User user) {
        for (User u : userList) {
            if (u.username.equals(user.username)) {
                return "用户名已存在";
            }
        }
        user.id = UUID.randomUUID().toString();
        userList.add(user);
        saveUsers();
        return "注册成功";
    }

    @PostMapping("/login")
    public String login(@RequestBody User user) {
        for (User u : userList) {
            if (u.username.equals(user.username) && u.password.equals(user.password)) {
                return u.id;
            }
        }
        return "用户名或密码错误";
    }
}
